package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.Book;
import com.bookstore.back.entity.Cart;
import com.bookstore.back.mapper.CartMapper;
import com.bookstore.back.service.BookService;
import com.bookstore.back.service.CartService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private UserContextUtil userContextUtil;

    @Autowired
    private BookService bookService;

    @Override
    public List<Map<String, Object>> getUserCartList() {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 查询用户购物车
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue())
                       .orderByDesc("created_at");
            
            List<Cart> cartList = this.list(queryWrapper);
            List<Map<String, Object>> result = new ArrayList<>();

            for (Cart cart : cartList) {
                // 获取图书详细信息
                Book book = bookService.getById(cart.getBookId());
                if (book != null && book.getStatus() == 1) { // 只返回上架的图书
                    Map<String, Object> cartItem = new HashMap<>();
                    cartItem.put("id", book.getId());
                    cartItem.put("title", book.getTitle());
                    cartItem.put("author", book.getAuthor());
                    cartItem.put("price", book.getPrice());
                    cartItem.put("cover", book.getCover());
                    cartItem.put("quantity", cart.getQuantity());
                    cartItem.put("selected", cart.getSelected() == 1);
                    cartItem.put("cartId", cart.getId());
                    result.add(cartItem);
                }
            }

            return result;
        } catch (Exception e) {
            log.error("获取用户购物车失败：{}", e.getMessage());
            throw new RuntimeException("获取购物车失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean addToCart(Integer bookId, Integer quantity) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 检查图书是否存在且上架
            Book book = bookService.getById(bookId);
            if (book == null || book.getStatus() != 1) {
                throw new RuntimeException("图书不存在或已下架");
            }

            // 检查库存
            if (book.getStock() < quantity) {
                throw new RuntimeException("库存不足");
            }

            // 检查是否已在购物车中
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue())
                       .eq("book_id", bookId);
            
            Cart existingCart = this.getOne(queryWrapper);
            
            if (existingCart != null) {
                // 如果已存在，更新数量
                int newQuantity = existingCart.getQuantity() + quantity;
                if (book.getStock() < newQuantity) {
                    throw new RuntimeException("库存不足");
                }
                existingCart.setQuantity(newQuantity);
                existingCart.setUpdatedAt(LocalDateTime.now());
                return this.updateById(existingCart);
            } else {
                // 如果不存在，新增记录
                Cart cart = new Cart();
                cart.setUserId(currentUserId.intValue());
                cart.setBookId(bookId);
                cart.setQuantity(quantity);
                cart.setSelected(1); // 默认选中
                cart.setCreatedAt(LocalDateTime.now());
                cart.setUpdatedAt(LocalDateTime.now());
                return this.save(cart);
            }
        } catch (Exception e) {
            log.error("添加商品到购物车失败：{}", e.getMessage());
            throw new RuntimeException("添加到购物车失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean updateCartQuantity(Integer bookId, Integer quantity) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            if (quantity <= 0) {
                // 如果数量为0或负数，删除该商品
                return removeFromCart(bookId);
            }

            // 检查库存
            Book book = bookService.getById(bookId);
            if (book == null || book.getStatus() != 1) {
                throw new RuntimeException("图书不存在或已下架");
            }

            if (book.getStock() < quantity) {
                throw new RuntimeException("库存不足");
            }

            // 更新购物车数量
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue())
                       .eq("book_id", bookId);
            
            Cart cart = this.getOne(queryWrapper);
            if (cart == null) {
                throw new RuntimeException("商品不在购物车中");
            }

            cart.setQuantity(quantity);
            cart.setUpdatedAt(LocalDateTime.now());
            return this.updateById(cart);
        } catch (Exception e) {
            log.error("更新购物车商品数量失败：{}", e.getMessage());
            throw new RuntimeException("更新数量失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean removeFromCart(Integer bookId) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 删除购物车记录
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue())
                       .eq("book_id", bookId);
            
            return this.remove(queryWrapper);
        } catch (Exception e) {
            log.error("从购物车删除商品失败：{}", e.getMessage());
            throw new RuntimeException("删除失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean clearCart() {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 清空用户购物车
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue());
            
            return this.remove(queryWrapper);
        } catch (Exception e) {
            log.error("清空购物车失败：{}", e.getMessage());
            throw new RuntimeException("清空购物车失败：" + e.getMessage());
        }
    }

    @Override
    public Integer getCartCount() {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return 0;
            }

            // 统计购物车商品数量
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue());
            
            List<Cart> cartList = this.list(queryWrapper);
            return cartList.stream().mapToInt(Cart::getQuantity).sum();
        } catch (Exception e) {
            log.error("获取购物车商品数量失败：{}", e.getMessage());
            return 0;
        }
    }

    @Override
    public boolean isInCart(Integer bookId) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return false;
            }

            // 检查商品是否在购物车中
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue())
                       .eq("book_id", bookId);
            
            return this.count(queryWrapper) > 0;
        } catch (Exception e) {
            log.error("检查商品是否在购物车中失败：{}", e.getMessage());
            return false;
        }
    }

    @Override
    @Transactional
    public boolean syncCartFromLocal(List<Map<String, Object>> cartItems) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            for (Map<String, Object> item : cartItems) {
                Integer bookId = (Integer) item.get("id");
                Integer quantity = (Integer) item.get("quantity");
                
                if (bookId != null && quantity != null && quantity > 0) {
                    // 检查图书是否存在且上架
                    Book book = bookService.getById(bookId);
                    if (book != null && book.getStatus() == 1) {
                        // 检查是否已在购物车中
                        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("user_id", currentUserId.intValue())
                                   .eq("book_id", bookId);
                        
                        Cart existingCart = this.getOne(queryWrapper);
                        
                        if (existingCart != null) {
                            // 如果已存在，更新数量（取较大值）
                            int newQuantity = Math.max(existingCart.getQuantity(), quantity);
                            if (book.getStock() >= newQuantity) {
                                existingCart.setQuantity(newQuantity);
                                existingCart.setUpdatedAt(LocalDateTime.now());
                                this.updateById(existingCart);
                            }
                        } else {
                            // 如果不存在，新增记录
                            if (book.getStock() >= quantity) {
                                Cart cart = new Cart();
                                cart.setUserId(currentUserId.intValue());
                                cart.setBookId(bookId);
                                cart.setQuantity(quantity);
                                cart.setSelected(1);
                                cart.setCreatedAt(LocalDateTime.now());
                                cart.setUpdatedAt(LocalDateTime.now());
                                this.save(cart);
                            }
                        }
                    }
                }
            }
            
            return true;
        } catch (Exception e) {
            log.error("同步本地购物车数据失败：{}", e.getMessage());
            throw new RuntimeException("同步购物车失败：" + e.getMessage());
        }
    }
}
